package com.flink.socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class SocketClient {
    private static final String SERVER_HOST = "localhost";
    private static final int SERVER_PORT = 9999;

    public static void main(String[] args) {
        try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             Scanner in = new Scanner(socket.getInputStream())) {

            System.out.println("已连接到服务端: " + SERVER_HOST + ":" + SERVER_PORT);

            // 启动一个线程接收服务端消息
            Thread receiveThread = new Thread(() -> {
                while (true) {
                    if (in.hasNextLine()) {
                        String serverMessage = in.nextLine();
                        System.out.println("服务端: " + serverMessage);
                    }
                }
            });
            receiveThread.setDaemon(true);
            receiveThread.start();

            // 主线程用于向服务端发送消息
            Scanner consoleScanner = new Scanner(System.in);
            while (true) {
                System.out.print("输入要发送给服务端的消息: ");
                String message = consoleScanner.nextLine();
                out.println(message);
            }
        } catch (IOException e) {
            System.err.println("客户端异常: " + e.getMessage());
        }
    }
}  